<template>
  <div class="page-miH page-bgBack" style="height: calc(100vh - 112px); overflow-y: auto">
    <PageHeader @back="goback()" subTitle="返回" id="target">
      <span>{{ moduleCode === "onJob" ? "入职" : moduleCode === "waitJob" ? "待入职" : "预登记" }}模板</span>
    </PageHeader>
    <div v-if="this.type === '3'" class="pt12 ph24 fs12">
      <a-alert banner closable>
        <div slot="message">若想自定义信息字段 请前往员工字段设置添加 <a href="#/staff/personalInfo/1">前往创建</a></div>
      </a-alert>
    </div>
    <div class="parentBox pt12">
      <div class="leftBox">
        <div class="leftBoxTop">
          <span class="leftBoxTopAddText">录入信息选择</span>
        </div>
        <div class="mt12 mb12">
          <a-input-search v-model="term" allowClear placeholder="搜索" style="width: 100%" @search="onSearch" />
        </div>
        <div v-if="showingList && showingList.length > 0" class="collapseShow" style="height: calc(100vh - 350px); overflow-y: auto">
          <a-collapse :active-key="newAllFieldKeys" :bordered="false">
            <template #expandIcon="props">
              <a-icon type="caret-right" :rotate="props.isActive ? 90 : 0" />
            </template>
            <a-collapse-panel v-for="z in showingList" :key="z.moduleName" :header="z.moduleName" :style="customStyle">
              <div class="nthClid">
                <Draggable
                  :group="{ name: 'form-draggable', pull: 'clone', put: false }"
                  :sort="false"
                  :animation="180"
                  ghostClass="moving"
                  :value="z.fields"
                  :clone="addFieldNameMove"
                  filter=".disabled"
                  tag="div"
                >
                  <template v-for="i in z.fields">
                    <div v-if="['probationDays', 'turnStraightDate'].includes(i.fieldCode)" :key="i.id" class="disabled wid45">
                      <a-tooltip placement="top" :title="`${i.fieldName}不可单独选择，选中员工状态后，将自动选择${i.fieldName}`">
                        <div class="leftBoxCon" style="background: #f5f5f5; color: rgba(0, 0, 0, 0.25)">
                          <div class="ovHid">{{ i.fieldName }}</div>
                        </div>
                      </a-tooltip>
                    </div>
                    <div v-else :key="i.id" :class="i.disabled ? 'disabled' : ''" class="wid45">
                      <div class="leftBoxCon">
                        <span class="icon iconfont icon-xuanzhong iconShow" v-if="i.isEdit === 0"></span>
                        <div class="ovHid" @click="addFieldName(i)">
                          <a-tooltip placement="top" :title="i.fieldName">{{ i.fieldName }}</a-tooltip>
                        </div>
                      </div>
                    </div>
                  </template>
                </Draggable>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </div>
      <div class="rightBox">
        <a-spin size="large" :spinning="spinning">
          <inTemplateForm
            class="pt24"
            ref="basic"
            :dataSource="basicData"
            :status="status === 'edit' && JSON.parse(this.$route.query.isDefault) ? true : false"
            :name="name"
            :dynamicData="{}"
            :formFields="basicFormJson.fields"
            :sortedKeysNew="basicFormJson.sortedKeys"
            :formConfig="{}"
            @changItemVal="changItemVal"
            @change="dynamicChange"
            @scrollTop="scrollToTop"
            @dragAdd="onDragAdd"
            @dragEnd="onDragEnd"
          />
        </a-spin>
      </div>
    </div>
  </div>
</template>

<script>
import inTemplateForm from "./inTemplateForm";
import Draggable from "vuedraggable";
import { loadAllFieldsReq, customTemplateFieldslistAll, customTemplatesAdd, customTemplatesEdit, listDefaultField } from "./api";
import { basicsPages } from "./dynamic";
import { mapState } from "vuex";
import _ from "lodash";
export default {
  components: {
    Draggable,
    inTemplateForm
  },
  data() {
    return {
      term: null,
      tempItem: null,
      newAllFields: [],
      newAllFieldKeys: [],
      oneLogin: true,
      customStyle: "border: 0; background: #fff",
      spinning: false,
      templateList: [],
      basicData: {},
      basicFormJson: { editable: true },
      form: this.$form.createForm(this, { name: "horizontal_login" })
    };
  },
  computed: {
    ...mapState(["hr"]),
    companyId() {
      return this.hr.companyId;
    },
    moduleCode() {
      return this.$route.query.moduleCode;
    },
    status() {
      return this.$route.query.status;
    },
    type() {
      return this.$route.query.type;
    },
    name() {
      return this.$route.query.name;
    },
    openTab() {
      return this.$route.query.openTab;
    },
    statusSHow() {
      return this.$route.query.statusSHow;
    },
    showingList() {
      if (this.newAllFields && this.newAllFields.length > 0 && this.templateList && this.templateList.length > 0) {
        const showNames = this.templateList.map((item) => item.fieldName);
        const res = [];
        this.newAllFields.forEach((mod) => {
          const fields = [];
          mod.fieldList.forEach((field) => {
            fields.push({
              ...field,
              isEdit: showNames.includes(field.fieldName) ? 0 : 1,
              disabled: showNames.includes(field.fieldName)
            });
          });
          mod.additionalFieldList.forEach((field) => {
            fields.push({
              ...field,
              isEdit: showNames.includes(field.fieldName) ? 0 : 1,
              disabled: showNames.includes(field.fieldName)
            });
          });
          res.push({
            ...mod,
            fields
          });
        });
        return res;
      }
      return [];
    }
  },
  created() {
    this.listDefaultField();
    this.loadAllFields();
  },
  methods: {
    onSearch: _.debounce(function (value) {
      this.loadAllFields(value);
    }, 1000),
    loadAllFields(term) {
      loadAllFieldsReq(this.type === "2" ? "site" : this.companyId, this.moduleCode, term)
        .then((res) => {
          this.newAllFields = res.data;
          this.newAllFieldKeys = term ? res.data.map((item) => item.moduleName) : [];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onDragEnd(newIndex, oldIndex) {
      const temp = [...this.templateList];
      const tempItem = { ...temp[oldIndex] };
      temp.splice(oldIndex, 1);
      temp.splice(newIndex, 0, tempItem);
      this.templateList = temp;
      this.getListCompanyModuleCodes(this.templateList);
    },
    onDragAdd(newIndex) {
      const temp = [...this.templateList];
      temp.splice(newIndex, 0, this.tempItem);
      this.templateList = temp;
      this.getListCompanyModuleCodes(this.templateList);
    },
    scrollToTop() {
      document.querySelector("#target").scrollIntoView();
    },
    // 删除和必填 操作
    changItemVal(item, test) {
      if (test === "del") {
        this.templateList = this.templateList.filter((key) => ![item].includes(key.fieldName));
        this.getListCompanyModuleCodes(this.templateList);
      } else {
        this.templateList = this.templateList.map((key) => {
          if (key.fieldName === item) {
            key.isNecessary = !key.isNecessary;
          }
          return key;
        });
        this.getListCompanyModuleCodes(this.templateList);
      }
    },
    // 添加模板字段
    addFieldNameMove(item) {
      this.tempItem = {
        ...item,
        isEdit: 1,
        isOpen: true
      };
      return item.fieldName;
    },
    addFieldName(e) {
      const data = this.templateList.filter((key) => key.fieldName === e.fieldName && key.isOpen);
      if (data.length === 0) {
        this.templateList = [
          ...this.templateList,
          {
            ...e,
            isEdit: 1,
            isOpen: true
          }
        ];
        this.getListCompanyModuleCodes(this.templateList);
      }
    },
    // 编辑
    customTemplateFieldslistAll() {
      customTemplateFieldslistAll({
        companyId: this.$route.query.statusSHow === "3" ? this.$store.state.hr.companyId : "site",
        templateId: this.$route.query.id
      })
        .then((res) => {
          const fl_add = res.data.additionalFieldList.filter((z) => z.isEdit === 1);
          const fl_sys = res.data.systemFieldList.filter((z) => z.isOpen === true);
          const fl = [...fl_sys, ...fl_add].sort((a, b) => {
            return a.sort - b.sort;
          });
          this.templateList = fl.map((z) => ({
            ...z,
            isNecessaryShow: z.isEdit === 0
          }));
          this.getListCompanyModuleCodes(this.templateList);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    listDefaultField() {
      listDefaultField({
        companyId: this.$route.query.statusSHow === "3" ? this.$store.state.hr.companyId : "site",
        moduleCode: this.moduleCode
      })
        .then((res) => {
          const data = [...res.data.systemFieldList];
          if (this.status === "add" && this.oneLogin) {
            this.templateList = data
              .filter((z) => z.isRequired)
              .map((z) => {
                z.isNecessaryShow = z.isNecessary;
                return z;
              });
            this.getListCompanyModuleCodes(this.templateList);
            this.oneLogin = false;
          }
          if (this.status === "edit" && this.oneLogin) {
            this.customTemplateFieldslistAll();
            this.oneLogin = false;
          } else {
            this.getListCompanyModuleCodes(this.templateList);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    dynamicChange(value, sortArray) {
      this.templateList = sortArray.map((i) => {
        const a = this.templateList.find((z) => z.fieldName === i);
        return a;
      });
      // type: 类型；1：系统 2：租户 3：用工单位
      if (this.type === "2") {
        this.templateList.map((i) => {
          i.templateId = null;
          i.companyId = null;
          return i;
        });
      } else {
        this.templateList.map((i) => {
          i.templateId = null;
          i.companyId = this.$store.state.hr.companyId;
          return i;
        });
      }
      const fieldAddDTOList =
        this.status === "add"
          ? this.templateList.map((z, index) => {
              z.isDefault = 0;
              z.id = null;
              z.isOpen = true;
              z.companyId = this.$route.query.statusSHow === "3" ? this.$store.state.hr.companyId : "site";
              z.sort = index + 1;
              return z;
            })
          : this.templateList.map((z, index) => {
              z.sort = index + 1;
              z.isOpen = true;
              z.companyId = this.$route.query.statusSHow === "3" ? this.$store.state.hr.companyId : "site";
              return z;
            });
      const data = {
        templateId: this.status === "add" ? null : this.$route.query.id,
        name: value.name,
        customFieldAddDTOList: fieldAddDTOList.filter((z) => z.fieldCode),
        additionalFieldsAddDTOList: fieldAddDTOList.filter((z) => !z.fieldCode),
        companyId: this.$route.query.statusSHow === "3" ? this.$store.state.hr.companyId : "site",
        isIssue: 0,
        moduleName: this.moduleCode === "onJob" ? "入职" : this.moduleCode === "waitJob" ? "待入职" : "预登记",
        moduleCode: this.moduleCode,
        type: this.type
      };
      this.spinning = true;
      if (this.status === "add") {
        customTemplatesAdd(data)
          .then((res) => {
            this.$message.success(res.msg);
            this.spinning = false;
            this.goback();
          })
          .catch((err) => {
            this.spinning = false;
            console.log(err);
          });
      } else {
        data.id = this.$route.query.id;
        data.type = this.$route.query.statusSHow;
        data.companyId = this.$route.query.statusSHow === "3" ? this.$store.state.hr.companyId : "site";
        data.isDefault = JSON.parse(this.$route.query.isDefault);
        customTemplatesEdit(data)
          .then((res) => {
            this.$message.success(res.msg);
            this.spinning = false;
            this.goback();
          })
          .catch((err) => {
            this.spinning = false;
            console.log(err);
          });
      }
    },
    goback() {
      if (this.statusSHow === "3") {
        this.$router.go(-1);
      } else {
        this.$router.push({ path: "/contractAdmin/ruzhi", query: { openTab: this.openTab } });
      }
    },
    // 获取展示数据
    getListCompanyModuleCodes(element) {
      const { fields, fieldKeys } = basicsPages("basic", [...(element && element.length > 0 ? element : [])]);
      this["basicFormJson"] = {
        editable: false,
        fields: fields,
        sortedKeys: fieldKeys
      };
    },
    mapShow(e) {
      const arr = e.map((z) => {
        const name = Object.keys(this.basicData).find((y) => y === z.fieldName);
        if (name) {
          z.isEdit = 0;
        }
        return z;
      });
      return arr;
    },
    search() {
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values);
        }
      });
    }
  }
};
</script>

<style lang="scss">
.collapseShow {
  .ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow {
    left: 0;
  }
  .ant-collapse > .ant-collapse-item > .ant-collapse-header {
    padding-top: 18px;
    padding-bottom: 18px;
    padding-left: 16px;
    padding-right: 0;
  }
  .ant-collapse-content > .ant-collapse-content-box {
    padding: 0;
  }
}
.newTemFormStyle {
  label {
    font-weight: 400;
  }
  .ant-form-explain {
    font-size: 12px;
  }
}
</style>
<style scoped lang="scss">
.parentBox {
  width: 100%;
  height: calc(100% - 110px);
  overflow-y: auto;
  margin-top: 0;
  position: relative;
}
.leftBox {
  width: 360px;
  position: absolute;
  padding: 0 24px;
  border-right: 1px solid #e8e8e8;
  height: calc(100% - 12px);
  overflow: scroll;
}
.rightBox {
  height: calc(100% - 12px);
  margin-left: 360px;
  overflow-y: auto;
}
.leftBoxTop {
  height: 40px;
  padding-bottom: 12px;
  border-bottom: 1px solid #dfdfdf;
  font-size: 16px;
  font-weight: 500;
  color: #3c3d43;
}
.leftBoxTopAddText {
  width: 50%;
  text-align: left;
  display: inline-block;
}
.leftBoxTopAdd {
  font-size: 14px;
  font-weight: 500;
  color: var(--primary);
  width: 50%;
  display: inline-block;
}
.leftBoxTopAddIcon {
  font-size: 20px;
  margin-right: 8px;
  vertical-align: sub;
}
.leftBoxCon {
  width: 100%;
  height: 38px;
  position: relative;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #dfdfdf;
  line-height: 38px;
  padding-left: 12px;
  padding-right: 12px;
  cursor: pointer;
  margin-bottom: 12px;
}
.iconShow {
  position: absolute;
  top: -11px;
  right: 0;
  color: var(--primary);
}
.nthClid .wid45:nth-child(even) .leftBoxCon {
  margin-left: 12px;
}
.colSelect {
  color: var(--primary);
  border: 1px solid var(--primary);
}
.wid45 {
  width: 48%;
  display: inline-block;
}
.leftBoxConIcon {
  font-size: 15px;
  color: #bfbfbf;
  display: inline-block;
}
.leftBoxConColRig {
  text-align: right;
  display: none;
  padding-right: 9px;
}
.leftBoxCon:hover {
  .leftBoxConColRig {
    display: block;
  }
}
.ovHid {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.yl {
  padding: 3px 6px;
  text-align: center;
  background: rgba(109, 105, 247, 0.1);
  font-size: 10px;
  color: #6a66f6;
  margin-left: 8px;
}
</style>
